<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Messenger Test</title>
	<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
	<style type='text/css'>
		.buddy {
			padding: 3px;
		}
		
		.buddy:hover {
			background-color: #aaa;
			color: white;
		}
	</style>
	<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
	<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
	<script src="/socket.io/socket.io.js"></script>
	<script>
		var Chat = {
			socket: null,
			from: null,
			to: null,
			gettingHistory: false,
			temp: [],
			
			ORDER_ASC: "ASC",
			ORDER_DESC: "DESC",
			
			clear: function() {
				Chat.to = null;
				
				$('#send').attr("disabled", "disabled");
			},
			
			createMessageId: function() {
				return Chat.from + '.' + (Number(new Date()) + (Math.floor(Math.random()*1000)));
			},
			
			show: function(data, order) {
				var output = '<div>' + data.from + ': ' + data.message + '</div>';
				
				if (order == "DESC") {
					$('#content').prepend(output);
				}
				else {
					$('#content').append(output);	
				}
			},
			
			showBuddy: function(name, unread) {
				$('#' + name).text(name + '(' + unread + ')');
			},
				
			showNotification: function(cell, order) {
				var message = '<div>' + cell.username + '님께서 연관글을 등록하였습니다: ' + cell.content + '</div>';
				
				if (order == "DESC") {
					$('#notification').prepend(message);
				}
				else {
					$('#notification').append(message);
				}				
			},
			
			log: function(message) {
				$('#log').prepend('<div>' + message + "</div>");
			}
		};
		
		$(document).ready(function() {
			var socket = io.connect();
			Chat.socket = socket;
			
			socket.on('login', function(result) {
				if (result) {
					// login successful
					$('#login_dialog').dialog('close');
					socket.emit('buddies');
					socket.emit('notificationList');
				}
				else {
					// invalid user
					alert('invalid user');
				}
			});
			
			socket.on('buddies', function(buddies) {
				for (var i = 0; i < buddies.length; i++) {
					var name = buddies[i].friend;
					var unread = buddies[i].unread;
					
					$('#buddies').append('<li id="' + name + '" class="buddy">' + name + '(' + unread + ')' + '</li>');
				}
			});
			
			socket.on('history', function(history) {
				history.rows.forEach(function(row) {
					Chat.show(row, Chat.ORDER_DESC);
				});
				
				Chat.showBuddy(history.to, history.unread);
				
				// if messages arrived while getting history, show them
				Chat.temp.forEach(function(data) {
					Chat.show(data);
				});
				
				Chat.temp = [];
				Chat.gettingHistory = false;
			});
			
			// add event handler
			socket.on('message', function(data) {
				if (data.from != Chat.from && data.from != Chat.to) {
					if (data.from != Chat.from) {
						Chat.showBuddy(data.from, data.unread);
					}
					
					// TODO: for this case, need to consider open/move to another tab in order not to get history again.
// 					$('#' + data.from).click();
				}
				else {
					if (Chat.gettingHistory) {
						Chat.temp.push(data);
					}
					else {
						Chat.show(data);
						
						// emit read event
						if (data.from == Chat.to) {
							socket.emit('read', {
								id: data.id,
								friend: data.from
							});
						}						
					}	
				}
			});
			
			socket.on('notification', function(cell) {
				Chat.showNotification(cell);
			});
			
			socket.on('notificationList', function(notifications) {
				notifications.forEach(function(notification) {
					Chat.showNotification(notification.data.cell, Chat.ORDER_DESC);
				});
			});
			
			$('#send').click(function() {
				if (!Chat.to) {
					alert('친구를 선택하세요.');
					return;
				}
				
				socket.emit('message', {
					id: Chat.createMessageId(),
					to: Chat.to,
					message: $('#message').val(),
					date: new Date().toUTCString()
				});
				
				$('#message').val('');
			});
			
			// login dialog
			$('#login_dialog').dialog({
				autoOpen: true,
				draggable: false,
				modal: true,
				title: 'Connect to XMPP',
				buttons: {
					"Connect": function() {
						$(document).trigger('connect', {
							username: $('#jid').val(),
							password: $('#password').val()
						});
					}
				}
			});
			
			$('.buddy').live('click', function() {
				Chat.to = $(this).attr('id');
				Chat.temp = [];
				Chat.gettingHistory = true;
				
				socket.emit('history', Chat.to);
				$('#content').html('');
				$('#to').html('<h3>To: ' + Chat.to + '</h3>');
			});
			
// 			var id = '<%= id %>';
// 			var password = '<%= password %>';
			
// 			if (id) {
// 				$('#jid').val(id);
// 				$('#password').val(password);
// 			}
		});
		
		$(document).bind('connect', function(ev, data) {
			if (Chat.socket) {
				Chat.socket.emit('login', data);
				Chat.from = data.username;
			}
				
		});
	</script>
</head>
<body>
	<h1>Messenger Test</h1>
	<p>Chat With Node.js</p>
	<hr/>
	
	<h3>Notification</h3>
	<div id="notification"></div>
	<hr/>
	
	<div id="buddylist">
		<p>Buddy List</p>
		<ui id="buddies"></ui>
	</div>

	<hr/>
	
	<div id="to"></div>
	<label>Message:</label><input type="text" id="message"/>
	<button id='send'>Send</button>
	<div id="content"></div>
	
	<hr/>
	<div id="log"></div>
	
	<!-- login dialog -->
	<div id="login_dialog" class="hidden">
		<label>JID:</label><input type="text" id="jid" value="dobin">
		<label>Password:</label><input type="password" id="password" value="03040205">
	</div>
</body>
</html>